// pages/course/video.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    courseId: null,
    sectionId: null,
    course: null,
    chapters: [],
    currentSection: null,
    isPlaying: false,
    currentTime: 0,
    duration: 0,
    playbackRate: 1.0,
    autoplay: true,
    studyProgress: 0,
    notes: [],
    showNoteModal: false,
    noteContent: '',
    isReview: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取课程ID和小节ID
    if (options.id) {
      const courseId = options.id;
      const sectionId = options.sectionId || null;
      const isReview = options.review === '1';
      
      this.setData({
        courseId,
        sectionId,
        isReview
      });
      
      // 加载课程数据
      this.loadCourseData();
      
      // 加载学习笔记
      this.loadNotes();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('courseVideo');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 恢复播放
    if (this.videoContext && this.data.isPlaying) {
      this.videoContext.play();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 暂停播放
    if (this.videoContext) {
      this.videoContext.pause();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 保存学习进度
    this.saveStudyProgress();
  },

  /**
   * 加载课程数据
   */
  loadCourseData() {
    // 模拟API调用
    setTimeout(() => {
      // 模拟课程数据
      const course = {
        id: this.data.courseId,
        title: 'Vue.js 3.0 从入门到精通',
        teacherName: '张老师'
      };
      
      // 模拟章节数据
      const chapters = [
        {
          id: 1,
          title: '第一章：Vue3基础入门',
          sections: [
            { 
              id: 101, 
              title: '1.1 课程介绍', 
              duration: '10:23', 
              isFree: true,
              isStudied: true,
              videoUrl: 'https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
              progress: 100
            },
            { 
              id: 102, 
              title: '1.2 开发环境搭建', 
              duration: '15:45', 
              isFree: true,
              isStudied: true,
              videoUrl: 'https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
              progress: 100
            },
            { 
              id: 103, 
              title: '1.3 Vue3项目创建与结构', 
              duration: '20:12', 
              isFree: false,
              isStudied: false,
              videoUrl: 'https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
              progress: 0
            }
          ]
        },
        {
          id: 2,
          title: '第二章：Vue3核心特性',
          sections: [
            { 
              id: 201, 
              title: '2.1 Composition API基础', 
              duration: '25:10', 
              isFree: false,
              isStudied: false,
              videoUrl: 'https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
              progress: 0
            },
            { 
              id: 202, 
              title: '2.2 响应式系统详解', 
              duration: '30:45', 
              isFree: false,
              isStudied: false,
              videoUrl: 'https://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400',
              progress: 0
            }
          ]
        }
      ];
      
      // 计算学习进度
      let totalSections = 0;
      let studiedSections = 0;
      
      chapters.forEach(chapter => {
        totalSections += chapter.sections.length;
        chapter.sections.forEach(section => {
          if (section.isStudied) {
            studiedSections++;
          }
        });
      });
      
      const studyProgress = totalSections > 0 ? Math.floor((studiedSections / totalSections) * 100) : 0;
      
      // 确定当前播放的小节
      let currentSection = null;
      
      if (this.data.sectionId) {
        // 如果指定了小节ID，则播放指定小节
        for (const chapter of chapters) {
          for (const section of chapter.sections) {
            if (section.id == this.data.sectionId) {
              currentSection = section;
              break;
            }
          }
          if (currentSection) break;
        }
      }
      
      // 如果没有指定小节或指定的小节不存在，则播放第一个小节
      if (!currentSection && chapters.length > 0 && chapters[0].sections.length > 0) {
        currentSection = chapters[0].sections[0];
      }
      
      this.setData({
        course,
        chapters,
        currentSection,
        studyProgress
      });
    }, 500);
  },
  
  /**
   * 加载学习笔记
   */
  loadNotes() {
    // 模拟API调用
    setTimeout(() => {
      // 模拟笔记数据
      const notes = [
        {
          id: 1,
          content: 'Vue3的Composition API比Options API更灵活，可以更好地组织代码逻辑。',
          createTime: '2023-06-15 14:30'
        },
        {
          id: 2,
          content: 'setup()函数是Composition API的入口，需要注意它的执行时机是在beforeCreate之前。',
          createTime: '2023-06-15 15:20'
        }
      ];
      
      this.setData({
        notes
      });
    }, 800);
  },
  
  /**
   * 保存学习进度
   */
  saveStudyProgress() {
    const { courseId, currentSection, currentTime, duration } = this.data;
    
    if (!courseId || !currentSection) return;
    
    // 计算当前小节的学习进度
    const progress = duration > 0 ? Math.floor((currentTime / duration) * 100) : 0;
    
    // 如果进度超过90%，则标记为已学习
    const isCompleted = progress >= 90;
    
    console.log(`保存学习进度: 课程ID=${courseId}, 小节ID=${currentSection.id}, 进度=${progress}%, 是否完成=${isCompleted}`);
    
    // TODO: 调用API保存学习进度
  },
  
  /**
   * 切换播放小节
   */
  switchSection(e) {
    const sectionId = e.currentTarget.dataset.id;
    
    // 保存当前学习进度
    this.saveStudyProgress();
    
    // 查找新的小节
    let newSection = null;
    
    for (const chapter of this.data.chapters) {
      for (const section of chapter.sections) {
        if (section.id == sectionId) {
          newSection = section;
          break;
        }
      }
      if (newSection) break;
    }
    
    if (newSection) {
      this.setData({
        currentSection: newSection,
        currentTime: 0
      });
      
      // 重新加载视频
      this.videoContext.stop();
      setTimeout(() => {
        this.videoContext.play();
      }, 100);
    }
  },
  
  /**
   * 视频播放事件
   */
  onVideoPlay() {
    this.setData({
      isPlaying: true
    });
  },
  
  /**
   * 视频暂停事件
   */
  onVideoPause() {
    this.setData({
      isPlaying: false
    });
  },
  
  /**
   * 视频结束事件
   */
  onVideoEnd() {
    this.setData({
      isPlaying: false
    });
    
    // 标记当前小节为已学习
    const { chapters, currentSection } = this.data;
    const updatedChapters = chapters.map(chapter => {
      const updatedSections = chapter.sections.map(section => {
        if (section.id === currentSection.id) {
          return { ...section, isStudied: true, progress: 100 };
        }
        return section;
      });
      return { ...chapter, sections: updatedSections };
    });
    
    // 计算新的学习进度
    let totalSections = 0;
    let studiedSections = 0;
    
    updatedChapters.forEach(chapter => {
      totalSections += chapter.sections.length;
      chapter.sections.forEach(section => {
        if (section.isStudied) {
          studiedSections++;
        }
      });
    });
    
    const studyProgress = totalSections > 0 ? Math.floor((studiedSections / totalSections) * 100) : 0;
    
    this.setData({
      chapters: updatedChapters,
      studyProgress
    });
    
    // 自动播放下一节
    this.playNextSection();
  },
  
  /**
   * 播放下一节
   */
  playNextSection() {
    const { chapters, currentSection } = this.data;
    let foundCurrent = false;
    let nextSection = null;
    
    // 查找下一节
    for (const chapter of chapters) {
      for (const section of chapter.sections) {
        if (foundCurrent) {
          nextSection = section;
          break;
        }
        if (section.id === currentSection.id) {
          foundCurrent = true;
        }
      }
      if (nextSection) break;
    }
    
    if (nextSection) {
      wx.showModal({
        title: '提示',
        content: '当前小节已学习完成，是否继续学习下一节？',
        confirmText: '继续学习',
        cancelText: '稍后再说',
        success: (res) => {
          if (res.confirm) {
            this.switchSection({ currentTarget: { dataset: { id: nextSection.id } } });
          }
        }
      });
    } else {
      wx.showToast({
        title: '恭喜，课程已学习完成！',
        icon: 'success'
      });
    }
  },
  
  /**
   * 视频播放进度更新事件
   */
  onTimeUpdate(e) {
    this.setData({
      currentTime: e.detail.currentTime,
      duration: e.detail.duration
    });
  },
  
  /**
   * 视频加载中事件
   */
  onVideoWaiting() {
    wx.showLoading({
      title: '视频加载中...'
    });
    
    setTimeout(() => {
      wx.hideLoading();
    }, 2000);
  },
  
  /**
   * 视频错误事件
   */
  onVideoError(e) {
    console.error('视频播放错误', e);
    wx.showToast({
      title: '视频加载失败',
      icon: 'error'
    });
  },
  
  /**
   * 修改播放速率
   */
  changePlayRate(e) {
    const rate = parseFloat(e.currentTarget.dataset.rate);
    this.setData({
      playbackRate: rate
    });
    this.videoContext.playbackRate(rate);
  },
  
  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },
  
  /**
   * 显示添加笔记输入框
   */
  showNoteInput() {
    this.videoContext.pause();
    this.setData({
      showNoteModal: true,
      noteContent: ''
    });
  },
  
  /**
   * 输入笔记内容
   */
  inputNote(e) {
    this.setData({
      noteContent: e.detail.value
    });
  },
  
  /**
   * 保存笔记
   */
  saveNote() {
    const { noteContent, currentSection, currentTime } = this.data;
    
    if (!noteContent.trim()) {
      wx.showToast({
        title: '笔记内容不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 模拟保存笔记
    const newNote = {
      id: Date.now(),
      content: noteContent,
      createTime: this.formatTime(new Date()),
      sectionId: currentSection.id,
      timePoint: Math.floor(currentTime)
    };
    
    const notes = [newNote, ...this.data.notes];
    
    this.setData({
      notes,
      showNoteModal: false
    });
    
    wx.showToast({
      title: '笔记保存成功',
      icon: 'success'
    });
    
    // 恢复播放
    setTimeout(() => {
      this.videoContext.play();
    }, 500);
  },
  
  /**
   * 取消添加笔记
   */
  cancelNote() {
    this.setData({
      showNoteModal: false
    });
    
    // 恢复播放
    setTimeout(() => {
      this.videoContext.play();
    }, 500);
  },
  
  /**
   * 删除笔记
   */
  deleteNote(e) {
    const noteId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这条笔记吗？',
      success: (res) => {
        if (res.confirm) {
          const notes = this.data.notes.filter(note => note.id !== noteId);
          
          this.setData({
            notes
          });
          
          wx.showToast({
            title: '笔记已删除',
            icon: 'success'
          });
        }
      }
    });
  },
  
  /**
   * 跳转到笔记时间点
   */
  jumpToNoteTime(e) {
    const timePoint = e.currentTarget.dataset.time;
    
    if (typeof timePoint === 'number') {
      this.videoContext.seek(timePoint);
      this.videoContext.play();
    }
  },
  
  /**
   * 格式化时间
   */
  formatTime(date) {
    const year = date.getFullYear();
    const month = this.padZero(date.getMonth() + 1);
    const day = this.padZero(date.getDate());
    const hour = this.padZero(date.getHours());
    const minute = this.padZero(date.getMinutes());
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },
  
  /**
   * 数字补零
   */
  padZero(num) {
    return num < 10 ? '0' + num : num;
  },
  
  /**
   * 格式化视频时长
   */
  formatDuration(seconds) {
    if (!seconds) return '00:00';
    
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    
    return `${this.padZero(minutes)}:${this.padZero(remainingSeconds)}`;
  }
})
  
  